package com.hxzy.controller.admin.dict;

import cn.hutool.core.util.StrUtil;
import com.alibaba.excel.EasyExcel;
import com.github.pagehelper.PageInfo;
import com.hxzy.common.annotates.RequiredRole;
import com.hxzy.common.constants.MarketConstants;
import com.hxzy.common.controller.BaseController;
import com.hxzy.common.enums.AckCode;
import com.hxzy.common.exception.ServiceException;
import com.hxzy.common.req.ExportIdsReq;
import com.hxzy.common.req.StatusChangeReq;
import com.hxzy.common.resp.R;
import com.hxzy.controller.admin.dict.req.*;
import com.hxzy.controller.admin.dict.resp.DictDataResp;
import com.hxzy.entity.SysDictData;
import com.hxzy.mapstruct.DictDataMapStruct;
import com.hxzy.service.SysDictDataService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.List;
import java.util.Map;
import java.util.Objects;

@Api(tags="后台-数据字典值Api")
@RestController
@RequestMapping(value = "/api/dictdata")
public class DictDataController extends BaseController {

    @Autowired
    private SysDictDataService dictDataService;


    @ApiOperation(value = "根据字典类型查询数据")
    @GetMapping(value = "/searchByDictTypes")
    public R<Map<String,List<DictDataResp>>>  searchByDictTypes(String[] dictTypes){
        if(dictTypes==null||dictTypes.length==0){
            return R.build(AckCode.SYSTEM_PARAM_FAIL);
        }

        Map<String,List<DictDataResp>> dataMap= this.dictDataService.searchByDictTypes(dictTypes);

        return R.okHasData(dataMap);
    }

    @ApiOperation(value = "分页查询")
    @GetMapping(value = "/data")
    public R<PageInfo<DictDataResp>> search(@Valid DictDataReq req){
        super.startPage(req);
        List<DictDataResp> list=this.dictDataService.search(req);
        return super.buildPageInfo(list);
    }

    @RequiredRole(role = MarketConstants.ACCOUNT_ADMIN_TYPE)
    @ApiOperation(value = "新增数据")
    @PostMapping
    public R addData(@RequestBody @Valid DictDataAddReq req){
        boolean result=this.dictDataService.addData(req);
        return result?R.ok(): R.build(AckCode.DATABASE_ERROR);
    }

    @ApiOperation(value = "根据主键查询")
    @GetMapping(value = "/{id}")
    public R<DictDataResp> findById(@PathVariable("id") Long id){
        if(Objects.isNull(id) || id.intValue()<=0){
            throw new ServiceException(AckCode.SYSTEM_PARAM_FAIL);
        }

        SysDictData db = this.dictDataService.getById(id);
        if(Objects.isNull(db)){
            throw new ServiceException(AckCode.NOT_FOUND_DATA);
        }

        DictDataResp convert = DictDataMapStruct.INSTANCE.convert(db);
        if(StrUtil.isBlank(convert.getListClass())){
            convert.setListClass("default");
        }

        return R.okHasData(convert);
    }


    @RequiredRole(role = MarketConstants.ACCOUNT_ADMIN_TYPE)
    @ApiOperation(value = "修改数据")
    @PutMapping
    public R updateData(@RequestBody @Valid DictDataEditReq req){
        boolean result=this.dictDataService.updateData(req);
        return result?R.ok(): R.build(AckCode.DATABASE_ERROR);
    }

    @RequiredRole(role = MarketConstants.ACCOUNT_ADMIN_TYPE)
    @ApiOperation(value = "更改状态")
    @PutMapping(value = "/change/status")
    public R changeStatus(@RequestBody @Valid StatusChangeReq req){
        boolean result=this.dictDataService.changeStatus(req);
        return result?R.ok(): R.build(AckCode.DATABASE_ERROR);
    }

    @ApiOperation(value = "导出excel",produces = "application/octet-stream")
    @PostMapping("/download")
    public void download(@RequestBody DictDataReq req, HttpServletResponse response) throws IOException {
        // 这里注意 有同学反应使用swagger 会导致各种问题，请直接用浏览器或者用postman
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setCharacterEncoding("utf-8");
        // 这里URLEncoder.encode可以防止中文乱码 当然和easyexcel没有关系
        String fileName = URLEncoder.encode("字典明细", "UTF-8").replaceAll("\\+", "%20");
        response.setHeader("Content-Disposition", "attachment; filename=" + fileName);
        //全查询
        List<DictDataResp> respList = this.dictDataService.search(req);

        //easyexcel最核心的代码
        EasyExcel.write(response.getOutputStream(), DictDataResp.class).sheet("字典明细").doWrite(respList);
    }

    @ApiOperation(value = "导出excel",produces = "application/octet-stream")
    @PostMapping("/download/choice")
    public void downloadIds(@RequestBody ExportIdsReq req, HttpServletResponse response) throws IOException {
        // 这里注意 有同学反应使用swagger 会导致各种问题，请直接用浏览器或者用postman
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setCharacterEncoding("utf-8");
        // 这里URLEncoder.encode可以防止中文乱码 当然和easyexcel没有关系
        String fileName = URLEncoder.encode("字典明细", "UTF-8").replaceAll("\\+", "%20");
        response.setHeader("Content-Disposition", "attachment; filename=" + fileName);
        //全查询
        List<DictDataResp> respList = this.dictDataService.exportExcel(req);

        //easyexcel最核心的代码
        EasyExcel.write(response.getOutputStream(), DictDataResp.class).sheet("字典明细").doWrite(respList);
    }


}
